﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;


namespace Smtp_server
{
    class Daemon_connection
    {
        private TcpClient tcpClient;
        private ILogger ilogger;
        private DBagent dbagent;

        public Daemon_connection(TcpClient tcpClient, ILogger ilogger, DBagent dbagent) 
        {
            this.tcpClient = tcpClient;
            this.ilogger = ilogger;
            this.dbagent = dbagent;
        }

        public void Run()
        {
            // Get a stream object for reading and writing
            NetworkStream stream = tcpClient.GetStream();


            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            ilogger.Write("Connected!\r\n");



            byte[] msg = System.Text.Encoding.ASCII.GetBytes(Macros.hello_message);
            stream.Write(msg, 0, msg.Length);

            int i;
            String replay;
            
            Parser parser = new Parser();
            // Loop to receive all the data sent by the client.
            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                // Translate data bytes to a ASCII string.
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

                ilogger.Write(">>" + data);
                replay=parser.Connection(data);

                msg = System.Text.Encoding.ASCII.GetBytes(replay);
                stream.Write(msg, 0, msg.Length);
                ilogger.Write("<<" + replay);

                if (parser.finish()==true)
                {
                    break;
                }
                    
            }
            if (parser.finish() == true)
            {
                Email email = parser.ExtractEmail();
                this.DoActions(email);
            }
            // Shutdown and end connection
            tcpClient.Close();
        }

        private void DoActions(Email email)
        {
            dbagent.Add(email);

            if (Macros.enableSms == true) 
            {
                Sms sms = new Sms();
                sms.Phone=email.Subject;
                sms.Body=email.BodyText;
                String state=sms.Send();
                ilogger.Write(state);
            }
            if (Macros.enableRelay == true) 
            {
                Relay relay = new Relay(ilogger);
                relay.Init();
                relay.Send(email);
                relay.Close();
            }



        }
    
    }
}
